﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using System.Globalization;

namespace System.Windows.Elements
{
    [ValueConversion(typeof(Color), typeof(String))]
    class ColorToHexStringConverter : IValueConverter
    {
        public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
        {
            var color = (Color)value;
            return String.Format("{0:x2}{1:x2}{2:x2}{3:x2}", color.A, color.R, color.G, color.B);
        }

        public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
        {
            var color = (String)value;
            Byte a, r, g, b;
            if (color.Length != 8 && color.Length != 6) return null;
            else
            {
                if (!Byte.TryParse(color.Substring(0, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out a)) return null;
                if (!Byte.TryParse(color.Substring(2, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out r)) return null;
                if (!Byte.TryParse(color.Substring(4, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out g)) return null;
                if (color.Length == 6) return Color.FromArgb(255, a, r, g);
                else
                {
                    if (!Byte.TryParse(color.Substring(6, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out b)) return null;
                    return Color.FromArgb(a, r, g, b);
                }
            }
        }
    }
}
